package com.celesea.framework.jwt;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtil {
    public static final String JWT_TOKEN = "JWT-TOKEN";
    public static final String SIGNING_KEY = "SIGNING_KEY";

    public static String generateToken(String subject) {
        return generateToken(SIGNING_KEY, subject);
    }

    public static String getSubject(HttpServletRequest httpServletRequest) {
        return getSubject(httpServletRequest, SIGNING_KEY);
    }

    public static String generateToken(String signingKey, String subject) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder = Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, signingKey);

        return builder.compact();
    }

    public static String getSubject(HttpServletRequest httpServletRequest, String signingKey) {
        String token = JwtCookieUtil.getValue(httpServletRequest);
        if (token == null) {
            return null;
        }
        return Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token).getBody().getSubject();
    }
}
